﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Leaky
{
    class LeakCreator
    {
        IntPtr val;

        ~LeakCreator()
        {
           System.Diagnostics.Debug.WriteLine("here");
        }
    }

    class Nasty
    {
        IntPtr val;

        ~Nasty()
        {
            System.Diagnostics.Debug.WriteLine("here");
        }
    }

    class ReallyNasty
    {
        IntPtr val;

        ~ReallyNasty()
        {
            System.Diagnostics.Debug.WriteLine("here");
        }
    }

    class AreYouNutsNasty
    {
        IntPtr val;

        ~AreYouNutsNasty()
        {
            System.Diagnostics.Debug.WriteLine("here");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            SubMethod();
            SubMethod2();

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            SubMethod();
            SubMethod2();

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            DeepNastyGenerate();
            DeepNastyGenerate2();

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }

        private static void DeepNastyGenerate2()
        {
            for (int i = 0; i < 10; ++i)
            {
                Nasty nasty = new Nasty();
                ReallyNasty reallyNasty = new ReallyNasty();

                if (i % 2 == 0)
                {
                    AreYouNutsNasty aynNasty = new AreYouNutsNasty();
                }
            }
        }

        private static void DeepNastyGenerate()
        {
            for (int i = 0; i < 10; ++i)
            {
                Nasty nasty = new Nasty();
                ReallyNasty reallyNasty = new ReallyNasty();

                if (i % 2 == 0)
                {
                    AreYouNutsNasty aynNasty = new AreYouNutsNasty();
                }
            }
        }

        private static void SubMethod()
        {
            LeakCreator lc = new LeakCreator();
            Console.WriteLine(lc.ToString());
        }

        private static void SubMethod2()
        {
            LeakCreator lc = new LeakCreator();
            Console.WriteLine(lc.ToString());
        }
    }
}
